package dao

import (
	"gitee.com/zhoulvvv/my_go_gateway/dto"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"time"
)

type ServiceInfo struct {
	Id          int       `json:"id" gorm:"primary_key" description:"自增主键"`
	LoadType    int       `json:"load_type" gorm:"column:load_type" description:"负载类型 0=http 1=tcp 2=grpc"`
	ServiceName string    `json:"service_name" gorm:"column:service_name" description:"服务名称"`
	ServiceDesc string    `json:"service_desc" gorm:"column:service_desc" description:"服务描述"`
	UpdatedAt   time.Time `json:"updated_at" gorm:"column:update_at" description:"更新时间"`
	CreatedAt   time.Time `json:"created_at" gorm:"column:create_at" description:"创建时间"`
	IsDelete    int       `json:"is_delete" gorm:"column:is_delete" description:"是否删除 0否 1是"`
}

func (si *ServiceInfo) TableName() string {
	return "gateway_service_info"
}

func (si *ServiceInfo) PageList(c *gin.Context, tx *gorm.DB, param *dto.ServiceListInput) ([]ServiceInfo, int64, error) {
	total := int64(0)
	list := []ServiceInfo{}

	query := tx.WithContext(c)
	query = query.Table(si.TableName())
	query = query.Where("is_delete = 0")
	if param.Info != "" {
		query = query.Where("(service_name like ? or service_desc like ?)", "%"+param.Info+"%", "%"+param.Info+"%")
	}
	// 分页查询 offset 就是偏移量 limit 就是每页数量 比如：limit 10(offset),20(limit)
	if err := query.Limit(param.PageSize).Offset(param.PageNo).Order("id desc").Find(&list).Error; err != nil && err != gorm.ErrRecordNotFound {
		return nil, total, err
	}
	// 获取总数
	query.Limit(param.PageSize).Offset(param.PageNo).Count(&total)
	return list, total, nil
}

// 查询服务类型数量
func (si *ServiceInfo) GroupByLoadType(c *gin.Context, tx *gorm.DB) ([]dto.PanelServiceStatItemOutput, error) {
	list := []dto.PanelServiceStatItemOutput{}
	query := tx.WithContext(c)
	query = query.Table(si.TableName())
	err := query.Where("is_delete = 0").Select("load_type,count(1) as value").
		Group("load_type").Scan(&list).Error
	if err != nil {
		return nil, err
	}
	return list, nil
}

func (si *ServiceInfo) Find(c *gin.Context, tx *gorm.DB, search *ServiceInfo) (*ServiceInfo, error) {
	serviceInfo := &ServiceInfo{}
	// 根据结构体查询
	err := tx.WithContext(c).Where("is_delete = 0").Where(search).First(serviceInfo).Error
	return serviceInfo, err
}

func (si *ServiceInfo) Save(c *gin.Context, tx *gorm.DB) error {
	err := tx.WithContext(c).Save(si).Error
	return err
}
